/*
 * 24/10/2011 - 02:16
 */
package org.nettyflux.remote;

import java.util.HashMap;
import java.util.Map;
import org.nettyflux.communicator.RemoteHost;
import org.nettyflux.mailbox.MailBox;
import org.nettyflux.mailbox.ReceiveListener;
import org.nettyflux.netmessages.MessageReceived;
import org.nettyflux.netmessages.NetworkMessage;

/**
 * @author Victor Williams Stafusa da Silva
 */
public class SkeletonRegistry {

    private final SkeletonStrategy strategy;
    private final MailBox<NetworkMessage> mailbox;
    private final Map<String, Object> bindedObjects;

    public SkeletonRegistry(SkeletonStrategy strategy, MailBox<NetworkMessage> mailbox) {
        this.mailbox = mailbox;
        this.strategy = strategy;
        this.bindedObjects = new HashMap<String, Object>();
        this.mailbox.addReceiveListener(MessageReceived.class, new SkeletonListener());
    }

    private class SkeletonListener implements ReceiveListener<MessageReceived<?>> {

        @Override
        public void receive(MessageReceived<?> message) {
            RemoteHost receiver = message.getSender();
            byte[] payload = message.getMessage();
            strategy.handle(SkeletonRegistry.this, mailbox, receiver, payload);
        }
    }

    public synchronized void bind(String name, Object object) {
        bindedObjects.put(name, object);
    }

    public synchronized void unbind(String name) {
        bindedObjects.remove(name);
    }

    public synchronized Object find(String name) {
        return bindedObjects.get(name);
    }
}
